﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace PoliticalClassifier.Web
{
	// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
	// visit http://go.microsoft.com/?LinkId=9394801

	/// <summary>
	/// Defines events for the MVC application.
	/// </summary>
	/// <remarks>
	///	This class is responsible for initializing and finalizing the MVC application.  During finalization, any lingering data files are deleted.
	/// </remarks>
	public class MvcApplication : System.Web.HttpApplication
	{
		/// <summary>
		/// Initializes the MVC application.
		/// </summary>
		protected void Application_Start()
		{
			AreaRegistration.RegisterAllAreas();

			WebApiConfig.Register(GlobalConfiguration.Configuration);
			FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
			RouteConfig.RegisterRoutes(RouteTable.Routes);
			BundleConfig.RegisterBundles(BundleTable.Bundles);
		}


		/// <summary>
		/// Handles errors in the MVC application.
		/// </summary>
		/// <remarks>
		/// The error handling checks for the error where a posted file exceeds the maximum request length limit.  When this error occurs, this handler clears the error and redirects the user to a custom view, which contains a user-friendly message and a field for uploading a new file.
		/// </remarks>
		/// <param name="sender">Error source.</param>
		/// <param name="args">Event arguments.</param>
		protected void Application_Error(object sender, EventArgs args)
		{
			Exception e = Server.GetLastError();

			// Custom error handling for uploaded files exceeding maximum size
			if ((e != null) && (e.Message == "Maximum request length exceeded."))
			{
				Server.ClearError();
				Server.TransferRequest("/Main/FileTooBig/");
			}
		}


		/// <summary>
		/// Finalizes the application.
		/// </summary>
		/// <remarks>
		/// On application shutdown, this method cleans up any uploaded files in the data directory.
		/// </remarks>
		protected void Application_End()
		{
			DirectoryInfo uploads = new DirectoryInfo(Server.MapPath("~/App_Data/Uploads/"));

			try
			{
				// Verify upload directory and cleanup all data files therein
				if ((uploads != null) && uploads.Exists)
					foreach (var file in uploads.GetFiles())
						file.Delete();
			}
			catch (Exception)
			{
			}
		}


		/// <summary>
		/// Finalizes a user session.
		/// </summary>
		/// <remarks>
		/// On session end, this method cleans up the user uploaded file in the data directory.
		/// </remarks>
		protected void Session_End()
		{
			string fileName = Path.Combine(Server.MapPath("~/App_Data/Uploads/"), Session.SessionID + ".xlsx");

			try
			{
				// Cleanup data file for session
				if (File.Exists(fileName))
					File.Delete(fileName);
			}
			catch (Exception)
			{
			}
		}
	}
}